package org.darchitect.nn.som;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class SOMController {

	private int defaultKohonenLayerWidth = 40;
	private int defaultInputVectorSize = 7;
	private double defaultD0tFactor = .5;
	private double defaultA0t = .1;
	private int defaultIterations = 5000;
	
	public SOM loadSOMFromWeightFile(String file) {
		double w[][][] = null;
		int n = 0;
		ArrayList<double[]> ll = new ArrayList<double[]>();
		try {
			BufferedReader in = new BufferedReader(new FileReader(file));
			String s = in.readLine();
			StringTokenizer tok;
			double dd[];
			while (s != null) {
				tok = new StringTokenizer(s);
				dd = new double[tok.countTokens()];
				n = dd.length;
				for (int i = 0; i < dd.length; i++)
					dd[i] = Double.parseDouble(tok.nextToken());
				ll.add(dd);
				s = in.readLine();
			}
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
		int dim = (int)Math.sqrt(ll.size());
		w = new double[dim][dim][n];
		for (int i = 0; i < dim; i++)
			for (int j = 0; j < dim; j++)
				for (int k = 0; k < n; k++)
					w[i][j][k] = ll.get(i * dim + j)[k];
		SOM som = new SOM(defaultKohonenLayerWidth, defaultInputVectorSize, defaultD0tFactor, defaultA0t, defaultIterations, w);
		return som;
	}
	
	public void saveSOMWeightsInFile(SOM som, String fileName) {
		double d[][][] = som.getWeights();
		try {
			PrintWriter out = new PrintWriter(new FileWriter(fileName));
			for (int i = 0; i < d.length; i++) { 
				for (int j = 0; j < d[i].length; j++) {
					for (int k = 0; k < d[i][j].length; k++) {
						if (k != 0)
							out.print(" ");
						out.print(d[i][j][k]);
					}
					out.println();
				}
			}
			out.close();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}
	
	public SOM createDefaultSOMInstance() {
		SOM som = new SOM(defaultKohonenLayerWidth, defaultInputVectorSize, defaultD0tFactor, defaultA0t, defaultIterations, null);
		return som;
	}
	
	public SOM createSOMInstance(int kohonenLayerWidth, int inputVectorSize,
			double d0tFactor, double a0t, int iterations) {
		SOM som = new SOM(kohonenLayerWidth, inputVectorSize, d0tFactor, a0t, iterations, null);
		return som;
	}

	public int getDefaultKohonenLayerWidth() {
		return defaultKohonenLayerWidth;
	}

	public int getDefaultInputVectorSize() {
		return defaultInputVectorSize;
	}

	public double getDefaultD0tFactor() {
		return defaultD0tFactor;
	}

	public double getDefaultA0t() {
		return defaultA0t;
	}

	public int getDefaultIterations() {
		return defaultIterations;
	}
	
}
